<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
    <ContentItemWrap>
      <template v-slot:title> 基本信息 </template>
      <template v-slot:content>
        <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120">
          <el-row>
            <el-col :span="8">
              <el-form-item label="企业名称" prop="tenantName">
                <el-input :maxlength="50" v-model="formData.tenantName" placeholder="请输入企业名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业简称" prop="shortName">
                <el-input :maxlength="50" v-model="formData.shortName" placeholder="请输入企业简称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="社会信用代码" prop="socialCreditCode">
                <el-input :maxlength="50" v-model="formData.socialCreditCode" placeholder="请输入社会信用代码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input :maxlength="10" v-model="formData.contactPerson" placeholder="请输入企业名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="contact">
                <el-input :maxlength="11" v-model="formData.contact" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业属性" prop="companyAttribute">
                <template v-slot:label>
                  <div class="icon_label">
                    <span>企业属性</span>
                    <el-tooltip effect="dark" placement="top" :raw-content="true" content="1. 销售：用于数据分析;
                    <br />2. 采购：用于短倒运费计算。">
                      <el-icon :size="16">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </div>
                </template>
                <el-select clearable style="width: 100%" multiple v-model="formData.companyAttribute"
                  placeholder="请选择企业属性">
                  <el-option v-for="item in getIntDictOptions(DICT_TYPE.COMPANY_ATTRIBUTE)" :key="item.value"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="行政地址" prop="admAddress">
                <el-col :span="4">
                  <el-form-item label="" prop="provinceAddress" label-width="0">
                    <el-select clearable style="width: 100%" v-model="formData.provinceAddress" placeholder="请选择省"
                      @change="changeProvince">
                      <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="" prop="cityAddress" label-width="10">
                    <el-select clearable style="width: 100%" v-model="formData.cityAddress" placeholder="请选择市"
                      @change="changeCity">
                      <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="" prop="countyAddress" label-width="10">
                    <el-select clearable style="width: 100%" v-model="formData.countyAddress" placeholder="请选择区/县"
                      @change="changeCounty">
                      <el-option v-for="item in countyList" :key="item.id" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="" prop="townsAddress" label-width="10">
                    <el-select clearable style="width: 100%" v-model="formData.townsAddress" placeholder="请选择街道"
                      @change="changeTowns">
                      <el-option v-for="item in townList" :key="item.id" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="详情地址" prop="simpleAddress
              " label-width="100">
                <el-input :maxlength="100" v-model="formData.simpleAddress" placeholder="请输入详情地址" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="经纬度" prop="lngLat">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="" prop="longitude" label-width="0">
                      <el-input :maxlength="20" type="number" v-model="formData.longitude" placeholder="请输入经度" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="" prop="latitude" label-width="10">
                      <el-input :maxlength="20" type="number" v-model="formData.latitude" placeholder="请输入纬度" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="行政区划" prop="administrativeDivision">
                <el-select clearable style="width: 100%" v-model="formData.administrativeDivision"
                  placeholder="请选择行政区划">
                  <el-option v-for="item in getIntDictOptions(DICT_TYPE.ADMINISTRATIVE_DIVISION)" :key="item.value"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业类别" prop="type">
                <el-select clearable style="width: 100%" v-model="formData.type" placeholder="请选择企业类别">
                  <el-option v-for="item in getIntDictOptions(DICT_TYPE.ENTER_TYPE)" :key="item.value"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="股权类别" prop="stockType">
                <el-select clearable style="width: 100%" v-model="formData.stockType" placeholder="请选择股权类别">
                  <el-option v-for="item in getIntDictOptions(DICT_TYPE.STOCK_TYPE)" :key="item.value"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="总产能" prop="capacity">
                <el-input :maxlength="50" v-model="formData.capacity" placeholder="请输入总产能" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="三方ID" prop="tenantId">
                <el-input :maxlength="20" :disabled="true" v-model="formData.tenantId" placeholder="请输入三方ID" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数据来源" prop="platformSource">
                <el-select clearable :disabled="true" style="width: 100%" v-model="formData.platformSource"
                  placeholder="请选择数据来源">
                  <el-option v-for="item in getIntDictOptions(DICT_TYPE.PLATFORM_SOURCE)" :key="item.value"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </ContentItemWrap>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { cloneDeep } from 'lodash'
  import * as coalMarket from '@/api/coalMarket'
  import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

  const message = useMessage()
  const emit = defineEmits(['success'])
  const dialogVisible = ref(false)
  const formLoading = ref(false)
  const dialogTitle = ref()
  const formRef = ref()
  const rowId = ref()
  const formData = ref({
    tenantName: undefined,
    shortName: undefined,
    socialCreditCode: undefined,
    contactPerson: undefined,
    contact: undefined,
    companyAttribute: [],
    provinceAddress: undefined,
    cityAddress: undefined,
    countyAddress: undefined,
    townsAddress: undefined,
    simpleAddress: undefined,
    longitude: undefined,
    latitude: undefined,
    administrativeDivision: undefined,
    type: undefined,
    stockType: undefined,
    capacity: undefined,
    tenantId: undefined,
    platformSource: 3,
  })
  const provinceList = ref([])
  const cityList = ref([])
  const countyList = ref([])
  const townList = ref([])

  const isValidPhoneNumber = (rule, phone, callback) => {
    if (!phone || /^1\d{10}$/.test(phone)) {
      callback()
    } else {
      callback(new Error('手机号码不正确'))
    }
  }

  const validMarkPoint = (rule, value, callback) => {
    if (!value || /^\d+(\.\d{1,10})?$/.test(value)) {
      return callback()
    }
    return callback(new Error('小数点后不能超10位'))
  }

  const formRules = reactive({
    tenantName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
    shortName: [{ required: true, message: '请输入企业简称', trigger: 'blur' }],
    companyAttribute: [{ required: true, message: '请选择企业属性', trigger: 'change' }],
    contact: [{ validator: isValidPhoneNumber, trigger: 'blur' }],
    longitude: [{ validator: validMarkPoint, trigger: 'blur' }],
    latitude: [{ validator: validMarkPoint, trigger: 'blur' }],
  })

  const open = async (id) => {
    resetForm()
    dialogVisible.value = true
    rowId.value = id
    if (id) {
      dialogTitle.value = '编辑'
    } else {
      dialogTitle.value = '新增'
    }
    await getAreaByCode(0, 1)
    if (id) {
      getCompanyById()
    }
  }

  const resetForm = () => {
    provinceList.value = []
    cityList.value = []
    countyList.value = []
    townList.value = []
    Object.keys(formData.value).forEach(key => {
      if (key === 'companyAttribute') {
        formData.value[key] = []
      } else if (key === 'platformSource') {
        formData.value[key] = 3
      } else {
        formData.value[key] = undefined
      }
    })
  }

  const getAreaByCode = async (code, type) => {
    const res = await coalMarket.getAreaByCode({
      fatherCode: code
    })
    if (type === 1) {
      provinceList.value = res || []
    }
    if (type === 2) {
      cityList.value = res || []
    }
    if (type === 3) {
      countyList.value = res || []
    }
    if (type === 4) {
      townList.value = res || []
    }
  }

  const changeProvince = (code) => {
    formData.value.cityAddress = undefined
    formData.value.countyAddress = undefined
    formData.value.townsAddress = undefined
    formData.value.simpleAddress = undefined
    getAreaByCode(code, 2)
  }

  const changeCity = (code) => {
    formData.value.countyAddress = undefined
    formData.value.townsAddress = undefined
    formData.value.simpleAddress = undefined
    getAreaByCode(code, 3)
  }

  const changeCounty = (code) => {
    formData.value.townsAddress = undefined
    formData.value.simpleAddress = undefined
    getAreaByCode(code, 4)
  }

  const changeTowns = () => {
    formData.value.simpleAddress = undefined
  }

  const getCompanyById = async () => {
    const res = await coalMarket.getCompanyById({ id: rowId.value })
    Object.keys(formData.value).forEach(key => {
      if (key === 'companyAttribute') {
        // 值为3时，代表选择采购、销售
        formData.value[key] = res[key] ? res[key] === 3 ? [1, 2] : [res[key]] : []
      } else if (['provinceAddress', 'cityAddress', 'countyAddress', 'townsAddress', 'administrativeDivision'].includes(key)) {
        if (res[key]) {
          formData.value[key] = res[key]
        }
        getAreaList(key)
      } else {
        formData.value[key] = res[key]
      }
    })
  }

  const getAreaList = (key) => {
    if (key === 'provinceAddress' && formData.value.provinceAddress) {
      getAreaByCode(formData.value.provinceAddress, 2)
    }
    if (key === 'cityAddress' && formData.value.cityAddress) {
      getAreaByCode(formData.value.cityAddress, 3)
    }
    if (key === 'countyAddress' && formData.value.countyAddress) {
      getAreaByCode(formData.value.countyAddress, 4)
    }
  }

  const submitForm = async () => {
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    formLoading.value = true
    if (rowId.value) {
      updateCompanyInfo()
    } else {
      createCompanyInfo()
    }
  }

  const updateCompanyInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['id'] = rowId.value
      data['address'] = getDetailAddress()
      data.companyAttribute = data.companyAttribute.length === 2 ? 3 : data.companyAttribute[0]
      const res = await coalMarket.updateCompanyInfo(data)
      if (res) {
        message.success('编辑成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  const createCompanyInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['address'] = getDetailAddress()
      data.companyAttribute = data.companyAttribute.length === 2 ? 3 : data.companyAttribute[0]
      const res = await coalMarket.createCompanyInfo(data)
      if (res) {
        message.success('新增成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  const getDetailAddress = () => {
    const provinceAddress = provinceList.value.find((e) => e.code === formData.value.provinceAddress)?.name
    const cityAddress = cityList.value.find((e) => e.code === formData.value.cityAddress)?.name
    const countyAddress = countyList.value.find((e) => e.code === formData.value.countyAddress)?.name
    const townsAddress = townList.value.find((e) => e.code === formData.value.townsAddress)?.name
    return `${provinceAddress || ''}${cityAddress || ''}${countyAddress || ''}${townsAddress || ''}${formData.value.simpleAddress || ''
      }`
  }

  defineExpose({ open })
</script>